
$(document).ready(function() {
    var globalurl = 'http://localhost/AIOphone/';
    var g_edit_addnew = 0;
    if ("onhashchange" in window) {
        //  alert("The browser supports the hashchange event!");
        //alert(location.hash);
    }

    function locationHashChanged() {
        $('.custom-nav .menu-list').each(function() {
            var that = $(this).first().find(">a");
            var p_hash = that.attr('href');
            if (that.attr('href') === location.hash) {
                var parent = $(that).parent();
                var sub = parent.find('> ul');
                parent.addClass('nav-active');
                sub.slideDown('200', function() {
                });
            }
        });

    }
    locationHashChanged();
    window.onhashchange = locationHashChanged;

    /*0 {hide} 1 {add new} 2{edit}*/

//    loadingAnimation();

    $("body").on('click', '#loadimage > div >a > img', function() {
        hashchange();
        var fulllink = $(this).attr('src');
        var shorlink = $(this).attr('alt');
        $("#img_link").val(shorlink);
        $("#img_display").attr('src', fulllink);
        $("#myModal").modal('hide');
    });
    /*
     * phần dùng chung
     */


    $(".sanpham #btn-themmoi").click(function() {
        prepairFormAddNew();
        $("[name='masp']", "#form_sanpham").prop('disabled', false);
    });
    $(".hangsx #btn-themmoi").click(function() {
        prepairFormAddNew();
        $("[name='mahangsx']", "#form_hangsx").prop('disabled', false);
    });
    $(".loaisp #btn-themmoi").click(function() {
        prepairFormAddNew();
        $("[name='matl']", "#form_loaisp").prop('disabled', false);
    });
    /*
     * 
     * @param {type} selector
     * @returns {undefined}
     */
    function scrollToElement(selector)
    {
        $('body').animate({
            scrollTop: $(selector).offset().top
        }, 1000);
    }
    /*
     * 
     */
    function prepairFormEdit() {
        //reset giá trị trên form
        $(".my-form form").trigger('reset');
        g_edit_addnew = 2;
        $("#my_submit").attr('value', "Sửa");
        $("#my_submit").text("Sửa");
        if (!$(".my-form").is(":visible")) {
            $(".my-form").toggle("show");
        }
    }
    function prepairFormAddNew() {
        
        g_edit_addnew = 1;
        //hiện form
        if (!$(".my-form").is(":visible")) {
            $(".my-form").toggle("show");
        }

        //reset giá trị trên form
        $(".my-form form").trigger('reset');
        $("#my_submit").attr('value', "Thêm mới");
        $("#my_submit").text("THêm mới");
        
    }
    /*
     * Hiện phần giao diện thêm mới/edit
     * @returns {undefined} 
     */
    function ShowElementToggle() {
        if (!$(".my-form").is(":visible")) {
            $(".my-form").toggle("show");
        }

    }
    /*
     * Sản phẩm
     */
    $(".loadimage").click(function() {
        $.ajax({
            type: "GET",
            url: globalurl + 'index.php/admin/view',
            dataType: 'json',
            data: {
            },
            success: function(data, status)
            {
                rs = [];
                $.each(data, function(i, item) {
                    //alert(item); 

                    rs.push("<div class='col-sm-6 col-xs-6 col-md-3'>\n\
<a href='#' class='thumbnail'>\n\
\n\
<img  alt='" + item + "' src='" + globalurl + "public/images/sanpham/" + item + "'>\n\
</a>\n\
</div>\n\
");

                });
//                alert(rs)
                $('#loadimage').html(rs);

                $('#myModal').modal('show');
            },
            error: function(data, status) {
                alert(status);
            }
        });

    });
    $("#xyz").click(function() {
        $.ajax({
            type: "GET",
            url: globalurl + 'index.php/admin/view',
            dataType: 'json',
            data: {
            },
            success: function(data, status)
            {
                rs = [];
                $.each(data, function(i, item) {
                    //alert(item); 

                    rs.push("<div class='col-xs-6 col-md-3'>\n\
<a href='#' class='thumbnail'>\n\
\n\
<img  alt='...' src='" + globalurl + "/public/images/sanpham/" + item + "'>\n\
</a>\n\
</div>\n\
");

                });
//                alert(rs)
                $('#son').html(rs);
                // alert(data.size());
//                alert(data);
            },
            error: function(data, status) {
                alert(status);
            }
        });
    });
    var g_masp, g_tensp, g_giaban, g_mahangsx, g_matl, g_hinhanh, g_is_noibat, g_is_new, g_tenhangsx;
    function IniSanphamToEdit(masp, tensp, giaban, mahangsx, matl, hinhanh, is_noibat, is_new) {
        $("[name='masp']", "#form_sanpham").val(masp);
        $("[name='tensp']", "#form_sanpham").val(tensp);
        $("[name='giaban']", "#form_sanpham").val(giaban);
        $("[name='mahangsx']", "#form_sanpham").val(mahangsx);
        $("[name='matl']", "#form_sanpham").val(matl);
        $("#img_display").attr("src", globalurl + "/public/images/sanpham/" + hinhanh)
        $("[name='hinhanh']", "#form_sanpham").val(hinhanh);
        $("[name='is_noibat']", "#form_sanpham").prop('checked', is_noibat == 1);
        $("[name='is_new']", "#form_sanpham").prop('checked', is_new == 1);
    }
    /*
     * 
     * @return các giá trị cần thiết để submit form sản phẩm
     */
    /*
     * các giá trị cần thiết để submit form sản phẩm
     * @param {int} a
     * @param {type} b
     * @returns {undefined}
     */
    function SetSanphamToSubmit() {
        g_masp = $("[name='masp']", this).val();
        g_tensp = $("[name='tensp']", this).val();
        g_giaban = $("[name='giaban']", this).val();
        g_mahangsx = $("[name='mahangsx']", this).val();
        g_matl = $("[name='matl']", this).val();
        g_hinhanh = $("[name='hinhanh']", this).val();
        g_is_noibat = $("[name='is_noibat']", this).is(':checked') ? 1 : 0;
        g_is_new = $("[name='is_new']", this).is(':checked') ? 1 : 0;
    }
    function SetHangSXToSubmit(){
        
    }
    /*
     * hàm dành cho add new hoặc update sản phẩm
     */
    $("#form_sanpham").submit(function(event) {
        event.preventDefault();
        SetSanphamToSubmit();
        var p_submit;
        if (g_edit_addnew == 1)
            p_submit = "add";//add new
        else
            p_submit = "update";//update
        $.ajax({
            type: 'POST',
            url: '',
            data: {
                submit: p_submit,
                masp: g_masp,
                tensp: g_tensp,
                giaban: g_giaban,
                mahangsx: g_mahangsx,
                matl: g_matl,
                hinhanh: g_hinhanh,
                is_noibat: g_is_noibat,
                is_new: g_is_new
            },
            success: function(data, status) {
                alert(status);
                alert(data);
            },
            error: function(data, status) {
                alert(status);
                alert(data);
            }
        });
    });
      $("#form_hangsx").submit(function(event) {
        event.preventDefault();
        
        var p_submit;
        if (g_edit_addnew == 1)
            p_submit = "add";//add new
        else
            p_submit = "update";//update
        $.ajax({
            type: 'POST',
            url: '',
            dataType:'Json',
            data: {
                submit: p_submit,
                mahangsx: $("[name='mahangsx']", this).val(),
                tenhangsx: $("[name='tenhangsx']", this).val()                
            },
            success: function(data, status) {
                if(data.result==true) alert("thanh cong"); else alert("co loi");
            },
            error: function(data, status) {
               // alert(status);
               // alert(data);
            }
        });
    });
     $("#form_loaisp").submit(function(event) {
        event.preventDefault();
        
        var p_submit;
        if (g_edit_addnew == 1)
            p_submit = "add";//add new
        else
            p_submit = "update";//update
        $.ajax({
            type: 'POST',
            url: '',
            dataType:'Json',
            data: {
                submit: p_submit,
                matl: $("[name='matl']", this).val(),
                tentl: $("[name='tentl']", this).val()                
            },
            success: function(data, status) {
                
                console.log(data.result);
                if(data.result==true) alert("thanh cong"); else alert("co loi");
            },
            error: function(data, status) {
                alert(status);
               // alert(data);
            }
        });
    });
    // TÌm kiếm sản phẩm
    $("#form_admin-search-sanpham").submit(function(event) {
        ajaxLoading("Please waiting");
        event.preventDefault();
        keyword = $(this).find("input[name='keyword']").val();
        console.log(keyword);
        $.ajax({
            url: '',
            type: 'POST',
            dataType: 'Json',
            data: {
                submit: 'search',
                keyword: keyword
            }, success: function(data, status) {
                result_table = "";
                $.each(data, function(i, item) {
                    result_table += "<tr><td>" + item.masp + "</td><td>" + item.tensp + "</td><td>" + item.giaban + "</td><td><input type='button' class='btn btn-primary edit' value='Edit'></td><td><input type='button' class='btn btn-danger delete' value='Delete'></td></tr>"
                });
                $("table.danhsach tbody").html(result_table);
                success();
            }, error: function(data, status) {
                alert(status);
            }
        });
    });
    $("#form_admin-search-hangsx").submit(function(event) {
        ajaxLoading("Please waiting");
        event.preventDefault();
        keyword = $(this).find("input[name='keyword']").val();
        console.log(keyword);
        $.ajax({
            url: '',
            type: 'POST',
            dataType: 'Json',
            data: {
                submit: 'search',
                keyword: keyword
            }, success: function(data, status) {
                result_table = "";
                $.each(data, function(i, item) {
                    result_table += "<tr><td>" + item.mahangsx + "</td><td>" + item.tenhangsx + "</td><td><input type='button' class='btn btn-primary edit' value='Edit'></td><td><input type='button' class='btn btn-danger delete' value='Delete'></td></tr>"
                });
                // scrollToElement("#test");

                //  alert(status);

                $("table.danhsach tbody").html(result_table);
                success();
            }, error: function(data, status) {
                alert(status);
            }
        });
    });
    $("#form_admin-search-loaisp").submit(function(event) {
        ajaxLoading("Please waiting");
        event.preventDefault();
        keyword = $(this).find("input[name='keyword']").val();
        console.log(keyword);
        $.ajax({
            url: '',
            type: 'POST',
            dataType: 'Json',
            data: {
                submit: 'search',
                keyword: keyword
            }, success: function(data, status) {
                result_table = "";
                $.each(data, function(i, item) {
                    result_table += "<tr><td>" + item.matl + "</td><td>" + item.tentl + "</td><td><input type='button' class='btn btn-primary edit' value='Edit'></td><td><input type='button' class='btn btn-danger delete' value='Delete'></td></tr>"
                });
                // scrollToElement("#test");

                //  alert(status);

                $("table.danhsach tbody").html(result_table);
                success();
            }, error: function(data, status) {
                alert(status);
            }
        });
    });
    var masp_danhsach;
    var g_id;
    $("body").on("mouseenter", "table.danhsach tbody tr", function() {
        g_id = $(this).find(":first-child").html();

    });
    /*
     * sự kiện nhấn vào edit sản phẩm để lấy thông tin sản phẩm
     */
    $("body").on("click", ".sanpham .danhsach .edit", function() {
        ajaxLoading("Please waiting to edit...");
        $.ajax({
            type: 'POST',
            url: '',
            dataType: 'Json',
            data: {
                submit: 'getsp',
                masp: g_id
            }, success: function(data, status) {
                g_edit_addnew = 2;
                $.each(data, function(i, item) {
                    console.log(i + ":" + item);
                });
                prepairFormEdit();
                IniSanphamToEdit(data.masp, data.tensp, data.giaban, data.mahangsx, data.matl, data.hinhanh, data.is_noibat, data.is_new);
                $("[name='masp']", "#form_sanpham").prop('disabled', true);
                success();
            }, error: function(data, status) {
                alert(status);
            }
        });

    });
     $("body").on("click", ".hangsx .danhsach .edit", function() {
        ajaxLoading("Please waiting to edit...");
        alert("hang");
        $.ajax({
            type: 'POST',
            url: '',
            dataType: 'Json',
            data: {
                submit: 'get',
                mahangsx: g_id
            }, success: function(data, status) {
                g_edit_addnew = 2;
                $.each(data, function(i, item) {
                    console.log(i + ":" + item);
                });
                prepairFormEdit();
                 $("[name='mahangsx']", "#form_hangsx").val(data.mahangsx);
                $("[name='tenhangsx']", "#form_hangsx").val(data.tenhangsx);

                $("[name='mahangsx']", "#form_hangsx").prop('disabled', true);
                success();
            }, error: function(data, status) {
                alert(status);
            }
        });

    });
     $("body").on("click", ".loaisp .danhsach .edit", function() {
        ajaxLoading("Please waiting to edit...");
        
        $.ajax({
            type: 'POST',
            url: '',
            dataType: 'Json',
            data: {
                submit: 'get',
                matl: g_id
            }, success: function(data, status) {
                g_edit_addnew = 2;
                $.each(data, function(i, item) {
                    console.log(i + ":" + item);
                });
                prepairFormEdit();
                 $("[name='matl']", "#form_loaisp").val(data.matl);
                $("[name='tentl']", "#form_loaisp").val(data.tentl);

                $("[name='matl']", "#form_loaisp").prop('disabled', true);
                success();
            }, error: function(data, status) {
                alert(status);
            }
        });

    });
    /*
     * sự kiện xóa 1 sản phẩm
     */
    $("body").on("click", ".sanpham .danhsach .delete", function() {
        if (confirm("Bạn có chắc chắn muốn xóa hay không?"))
        {
            var current_row = $(this).parents('tr');
            ajaxLoading("Deleting...");
            $.ajax({
                type: 'POST',
                url: '',
                dataType: 'Json',
                data: {
                    submit: 'delete',
                    masp: g_id
                }, success: function(data, status) {
                    ajaxLoadCompleted();
                    if (data.result == true) {
                        $(current_row).remove();
                        success();
                        // alert("succeess");
                    }
                    else
                        alert("error");
                    // alert("success");
                }, error: function(data, status) {

                }
            });

        }

    });
    $("body").on("click", ".hangsx .danhsach .delete", function() {
        alert(g_id);
        if (confirm("Bạn có chắc chắn muốn xóa hay không?"))
        {
            var current_row = $(this).parents('tr');
            ajaxLoading("Deleting...");
            $.ajax({
                type: 'POST',
                url: '',
                dataType: 'Json',
                data: {
                    submit: 'delete',
                    mahangsx: g_id
                }, success: function(data, status) {
                    /// alert(data);
                    ajaxLoadCompleted();
                    if (data.result == true) {
                        $(current_row).remove();
                        success();
                    }
                    else
                        alert("Lỗi khóa ngoại!");

                }, error: function(data, status) {
                    // alert(data.result);
                    alert(status);
                }
            });

        }

    });
    $("body").on("click", ".loaisp .danhsach .delete", function() {
        alert(g_id);
        if (confirm("Bạn có chắc chắn muốn xóa hay không?"))
        {
            var current_row = $(this).parents('tr');
            ajaxLoading("Deleting...");
            $.ajax({
                type: 'POST',
                url: '',
                dataType: 'Json',
                data: {
                    submit: 'delete',
                    matl: g_id
                }, success: function(data, status) {
                    /// alert(data);
                    ajaxLoadCompleted();
                    if (data.result == true) {
                        $(current_row).remove();
                        success();
                    }
                    else
                        alert("Lỗi khóa ngoại!");

                }, error: function(data, status) {
                    // alert(data.result);
                    alert(status);
                }
            });

        }

    });


    /*
     * hãng sản xuất
     */
    // TÌm kiếm 
    
    /*
     * submit
     */
    $("#form_hangsx").submit(function(event) {
        event.preventDefault();
        SetSanphamToSubmit();
        var p_submit;
        if (g_edit_addnew == 1)
            p_submit = "add";//add new
        else
            p_submit = "update";//update
        $.ajax({
            type: 'POST',
            url: '',
            data: {
                submit: p_submit,
                masp: g_masp,
                tensp: g_tensp,
                giaban: g_giaban,
                mahangsx: g_mahangsx,
                matl: g_matl,
                hinhanh: g_hinhanh,
                is_noibat: g_is_noibat,
                is_new: g_is_new
            },
            success: function(data, status) {
                alert(status);
                alert(data);
            },
            error: function(data, status) {
                alert(status);
                alert(data);
            }
        });
    });
    function SetHangsxToSubmit() {
        g_mahangsx = $("[name='mahangsx']", this).val();
        g_tenhangsx = $("[name='tenhangsx']", this).val();
    }
    /*
     * sự kiện nhấn vào edit sản phẩm để lấy thông tin hãng sx
     */
   
    /*
     * sự kiện xóa 1 hãng sản xuất
     */
    
    $("html").niceScroll({styler: "fb", cursorcolor: "#7266ba", cursorwidth: '10', cursorborderradius: '2px', spacebarenabled: false, cursorborder: '0', zindex: '1000'});
    $(".left-side").niceScroll({styler: "fb", cursorcolor: "#7266ba", cursorwidth: '6', cursorborderradius: '2px', spacebarenabled: false, cursorborder: '0'});
    $(".left-side").getNiceScroll();
    $(".custom-nav .menu-list > a").click(function(event) {
        /* Act on the event */
        event.preventDefault();
        location.hash = $(this).attr('href');
        var parent = $(this).parent();
        var sub = parent.find('> ul');
        /*neu menu da bi thu nho*/
        if ($('body').hasClass('left-side-collapsed'))
        {
            //if(sub.is(':visible'))
            //	alert('xxx');else alert 'xxxyyy';

        }
        /*neu menu trai hien ra*/
        else
        {
            if (sub.is(':visible'))
            {
                sub.slideUp('200', function() {
                    parent.removeClass('nav-active');
                });
            }
            else {

                an();
                parent.addClass('nav-active');
                sub.slideDown('200', function() {

                });
            }

        }
        //alert('xxx');
    });
    function an() {
        $('.menu-list').each(function(index, el) {
            var menu = $(this);
            if (menu.hasClass('nav-active')) {

                menu.find('> ul').slideUp(200, function() {
                    menu.removeClass('nav-active');
                });
            }
        });
    }
    $(".custom-nav > li").hover(function() {
        $(this).addClass('nav-hover');
    }, function() {
        $(this).removeClass('nav-hover');
    });
    $(".my-scroll").click(function() {
        //alert( $(this.name).offset().top - 60);
        $("html, body").animate({
            scrollTop: $(this.name).offset().top - 60
        }, 'slow', function() {
            //alert('succes!');
        });
    });
    // $('.dropdown-toggle').dropdown();
    $("select").selectpicker({
        style: 'btn-info',
        size: 4
    });

    function ajaxLoading(text) {
        $("#ajax_loading").css({
            display: 'block'
        });
        $("#ajax_loading label").html("<span class='glyphicon glyphicon-refresh glyphicon-refresh-animate'></span>" + text);
    }
    function ajaxLoadCompleted() {

        // $("#ajax_loading").hide();
    }
    /*
     * loading animation
     */
    function loadingAnimation()
    {
        $("#mask_loading").css({
            display: 'block'
        });
    }
    function hideLoadingAnimation() {
        $("#mask_loading").css({
            display: 'none'
        });
    }
    function success()
    {
        //$("#ajax_loading").hide("")
        $("#ajax_loading").toggle("slow", function() {
            $(this).hide();
        });
    }

});